package com.ly.heart.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.ReturnPage;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.KingBaseBusinessGroupDetailEntity;
import com.ly.heart.domain.KingBaseBusinessGroupEntity;
import com.ly.heart.domain.dto.KingBaseBusinessGroupQueryDto;
import com.ly.heart.domain.vo.KingBaseBusinessGroupVo;
import com.ly.heart.mapper.KingBaseBusinessGroupMapper;
import com.ly.heart.service.IKingBaseBusinessGroupDetailService;
import com.ly.heart.service.IKingBaseBusinessGroupService;
import com.ly.heart.util.ChineseToPinyin;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.system.service.ISysDeptService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


/**
 * 金蝶-业务组类型Service业务层处理
 *
 * @author cxl
 * @date 2024-06-20
 */
@Service
public class KingBaseBusinessGroupServiceImpl extends ServiceImpl<KingBaseBusinessGroupMapper, KingBaseBusinessGroupEntity> implements IKingBaseBusinessGroupService {

    @Resource
    private KingBaseBusinessGroupMapper kingBaseBusinessGroupMapper;
    @Resource
    private IKingBaseBusinessGroupDetailService kingBaseBusinessGroupDetailService;
    @Resource
    private ISysDeptService sysDeptService;

    /**
     * 查询金蝶-业务组类型
     *
     * @param id 金蝶-业务组类型ID
     * @return 金蝶-业务组类型
     */
    @Override
    public KingBaseBusinessGroupEntity selectKingBaseBusinessGroupEntityById ( String id ) {
        KingBaseBusinessGroupEntity businessGroup = kingBaseBusinessGroupMapper.selectKingBaseBusinessGroupEntityById ( id );
        List<KingBaseBusinessGroupDetailEntity> groupDetailList = kingBaseBusinessGroupDetailService.list ( new QueryWrapper<KingBaseBusinessGroupDetailEntity> ().eq ( "business_group_id", id ) );
        if ( ! CollectionUtils.isEmpty ( groupDetailList ) ) {
            businessGroup.setBusinessGroupDetailList ( groupDetailList );
        }
        return businessGroup;
    }

    /**
     * 查询金蝶-业务组类型列表
     *
     * @param kingBaseBusinessGroupEntity 金蝶-业务组类型
     * @return 金蝶-业务组类型
     */
    @Override
    public AjaxResult selectKingBaseBusinessGroupEntityList ( KingBaseBusinessGroupEntity kingBaseBusinessGroupEntity ) {
        Page<KingBaseBusinessGroupEntity> page = this.page ( new Page<> ( kingBaseBusinessGroupEntity.getPage (), kingBaseBusinessGroupEntity.getLimit () ), new LambdaQueryWrapper<KingBaseBusinessGroupEntity> ().eq ( KingBaseBusinessGroupEntity :: getIsUsed, ConstUtil.IS_USED_YES ) );
        List<KingBaseBusinessGroupEntity> businessGroupList = page.getRecords (); //kingBaseBusinessGroupMapper.selectKingBaseBusinessGroupEntityList ( kingBaseBusinessGroupEntity );
        if ( ! CollectionUtils.isEmpty ( businessGroupList ) ) {
            businessGroupList.forEach ( businessGroup -> {
                List<KingBaseBusinessGroupDetailEntity> groupDetailList = kingBaseBusinessGroupDetailService.list ( new QueryWrapper<KingBaseBusinessGroupDetailEntity> ().eq ( "business_group_id", businessGroup.getId () ) );
                if ( ! CollectionUtils.isEmpty ( groupDetailList ) ) {
                    businessGroup.setBusinessGroupDetailList ( groupDetailList );
                }
            } );
        }
        return AjaxResult.success ( page );
    }

    /**
     * 新增金蝶-业务组类型
     *
     * @param kingBaseBusinessGroupEntity 金蝶-业务组类型
     * @return 结果
     */
    @Override
    public int insertKingBaseBusinessGroupEntity ( KingBaseBusinessGroupEntity kingBaseBusinessGroupEntity ) {
        String businessGroupId = SnowflakeIdWorker.getInstance ().nextStringId ();
        String userId = SecurityUtils.getLoginUser ().getUser ().getUserId ();
        Date nowDate = DateUtils.getNowDate ();
        kingBaseBusinessGroupEntity.setCreateTime ( nowDate );
        kingBaseBusinessGroupEntity.setId ( businessGroupId );
        kingBaseBusinessGroupEntity.setUserId ( userId );
        if(StringUtils.isEmpty(kingBaseBusinessGroupEntity.getDocCode())){
            String companyId = CurrentUserUtil.getCompanyId();
            SysDept sysDept = sysDeptService.getById(companyId);
            int count = this.count();
            String countStr = String.format("%06d", count);
            String firstLetter = ChineseToPinyin.getFirstLetter(sysDept.getDeptName());
            String docCode = firstLetter.concat("_YWZ_").concat(countStr);
            kingBaseBusinessGroupEntity.setDocCode(docCode);
        }
        if ( ! CollectionUtils.isEmpty ( kingBaseBusinessGroupEntity.getBusinessGroupDetailList () ) ) {
            List<KingBaseBusinessGroupDetailEntity> groupDetailList = kingBaseBusinessGroupEntity.getBusinessGroupDetailList ();
            groupDetailList.forEach ( groupDetail -> {
                groupDetail.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                groupDetail.setBusinessGroupId ( businessGroupId );
                int count = this.count ();
                groupDetail.setBusinessCode ( "YWZ".concat ( String.format ( "%08d", count ) ) );
                groupDetail.setUserId ( userId );
                groupDetail.setCreateTime ( nowDate );
                kingBaseBusinessGroupDetailService.save ( groupDetail );
            } );
        }
        boolean save = this.save ( kingBaseBusinessGroupEntity );
        return save ? 1 : 0;
    }

    /**
     * 修改金蝶-业务组类型
     *
     * @param kingBaseBusinessGroupEntity 金蝶-业务组类型
     * @return 结果
     */
    @Override
    public int updateKingBaseBusinessGroupEntity ( KingBaseBusinessGroupEntity kingBaseBusinessGroupEntity ) {
        kingBaseBusinessGroupEntity.setChangeTime ( DateUtils.getNowDate () );
        kingBaseBusinessGroupDetailService.remove ( new QueryWrapper<KingBaseBusinessGroupDetailEntity> ().eq ( "business_group_id", kingBaseBusinessGroupEntity.getId () ) );
        if ( ! CollectionUtils.isEmpty ( kingBaseBusinessGroupEntity.getBusinessGroupDetailList () ) ) {
            List<KingBaseBusinessGroupDetailEntity> groupDetailList = kingBaseBusinessGroupEntity.getBusinessGroupDetailList ();
            groupDetailList.forEach ( groupDetail -> {
                groupDetail.setBusinessGroupId ( kingBaseBusinessGroupEntity.getId () );
                groupDetail.setUserId ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
                groupDetail.setCreateTime ( DateUtils.getNowDate () );
                kingBaseBusinessGroupDetailService.save ( groupDetail );
            } );
        }
        return kingBaseBusinessGroupMapper.updateKingBaseBusinessGroupEntity ( kingBaseBusinessGroupEntity );
    }

    /**
     * 批量删除金蝶-业务组类型
     *
     * @param ids 需要删除的金蝶-业务组类型ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteKingBaseBusinessGroupEntityByIds ( String[] ids ) {
        List<KingBaseBusinessGroupEntity> list = this.list ( new LambdaQueryWrapper<KingBaseBusinessGroupEntity> ().
                in ( KingBaseBusinessGroupEntity :: getId, ids ) );
        List<String> idList = list.stream ().filter ( business -> business.getIsDel () == 1 ).map ( KingBaseBusinessGroupEntity :: getId ).collect ( Collectors.toList () );
        //不可删除的银行名称集合
        StringBuilder stringBuilder = new StringBuilder ( "【" );
        list.forEach ( business -> {
            if ( business.getIsDel () == 2 ) {
                stringBuilder.append ( business.getBusinessGroupType () );
            }
        } );
        stringBuilder.append ( "】" );
        boolean update = this.update ( new LambdaUpdateWrapper<KingBaseBusinessGroupEntity> ().set ( KingBaseBusinessGroupEntity :: getIsUsed, ConstUtil.IS_USED_NO ).in ( KingBaseBusinessGroupEntity :: getId, idList ) );
        if ( ! update ) {
            throw new CustomException ( "删除业务组失败！" );
        }
        String str = "删除业务组成功";
        if ( list.size () > 0 ) {
            str.concat ( "，其中" ).concat ( stringBuilder.toString () ).concat ( "被引用，不可删除" );
        }
        return AjaxResult.success ( str );
    }

    /**
     * 删除金蝶-业务组类型信息
     *
     * @param id 金蝶-业务组类型ID
     * @return 结果
     */
    @Override
    public int deleteKingBaseBusinessGroupEntityById ( String id ) {
        kingBaseBusinessGroupDetailService.remove ( new QueryWrapper<KingBaseBusinessGroupDetailEntity> ().eq ( "business_group_id", id ) );
        return kingBaseBusinessGroupMapper.deleteKingBaseBusinessGroupEntityById ( id );
    }

    @Override
    public AjaxResult disabled ( String id ) {
        KingBaseBusinessGroupEntity baseBusinessGroupEntity = this.getById ( id );
        if ( baseBusinessGroupEntity == null ) {
            throw new CustomException ( "无此业务组" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<KingBaseBusinessGroupEntity> ().
                set ( KingBaseBusinessGroupEntity :: getChangeTime, DateUtils.getNowDate () ).
                set ( KingBaseBusinessGroupEntity :: getIsDisabled, baseBusinessGroupEntity.getIsDisabled () == 1 ? 2 : 1 ).
                eq ( KingBaseBusinessGroupEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( baseBusinessGroupEntity.getIsDisabled () == 1 ? "禁用业务组失败！" : "解禁业务组失败！" );
        }
        return AjaxResult.success ();
    }

    @Override
    public AjaxResult getBusinessGroupList(KingBaseBusinessGroupQueryDto queryDto){
        List<KingBaseBusinessGroupVo> list = kingBaseBusinessGroupDetailService.getBusinessGroupDialog(queryDto);
        Page<KingBaseBusinessGroupVo> page = new Page<>(queryDto.getPage(),queryDto.getLimit());
        return AjaxResult.success(ReturnPage.getReturnPage(page,list));
    }


}
